﻿#region Copyright information
// 
// Copyright © 2012-2013 Yongkee Cho. All rights reserved.
// 
// This code is a part of the SubnetworkToolkit and governed under the terms of the
// GNU Lesser General  Public License (LGPL) version 2.1 which accompanies this distribution.
// For more information on the LGPL, please visit http://bol.codeplex.com/license.
// 
// - Filename: Program.cs
// - Author: Yongkee Cho
// - Email: yongkeecho@outlook.com
// - Date Created: 2013-01-30 2:55 PM
// - Last Modified: 2013-01-30 3:21 PM
// 
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using CommandLine;
using SubnetworkToolkit.IO;

namespace SubnetworkToolkit.Filter
{
    static class Program
    {
        static void Main(string[] args)
        {
            var options = new Options();

            try
            {
                // parse arguments
                var parser = new CommandLineParser(new CommandLineParserSettings(Console.Error));
                parser.ParseArguments(args, options);

                if (args.Length == 0 || args[0] == "-h")
                    Console.Error.Write(options.GetUsage());
                else
                {
                    var gmt = options.GmtFile;
                    var gr = new GmtReader(gmt);
                    var geneSets = gr.Read();
                    gr.Close();

                    var geneSet1 = geneSets.First();
                    var writeSymbol = !geneSet1.Genes.All(x => String.IsNullOrEmpty(x.Symbol));

                    var include = options.Include;
                    var exclude = options.Exclude;
                    var filteredGeneSets = new List<GeneSet>();

                    foreach (var geneSet in geneSets)
                    {
                        if (writeSymbol)
                        {
                            var geneSymbols = geneSet.Genes.Select(x => x.Symbol).ToList();
                            if (geneSymbols.Any(include.Contains) && !geneSymbols.Any(exclude.Contains))
                                filteredGeneSets.Add(geneSet);
                        }
                        else
                        {
                            var geneIds = geneSet.Genes.Select(x => x.Id.ToString(CultureInfo.InvariantCulture)).ToList();
                            if (geneIds.Any(include.Contains) && !geneIds.Any(exclude.Contains))
                                filteredGeneSets.Add(geneSet);
                        }
                    }

                    var outputFile = options.OutputFile;
                    var gw = new GmtWriter(outputFile, filteredGeneSets, writeSymbol);
                    gw.Write();
                    gw.Close();
                }
            }
            catch (Exception ex)
            {
                Console.Error.Write(ex.Message);
            }
        }
    }
}
